import axios from "axios";

import { defineStore } from 'pinia'

export const useFenleiStore = defineStore('fenlei', {
    state: () => {
        return {
            fenleiList: []
        }
    },
    actions: {
        FENLEI() {
            axios.get("https://api-hmugo-web.itheima.net/api/public/v1/categories").then(res => {
                this.fenleiList = res.data.message
            })
        }
    },
})

export const useCartStore = defineStore('cart',{
    state:()=>{
        return {
            cartList:[]
        }
    },
    persist: true,
    actions:{
        ADD_CART_ITEM(cartItem){
            const goodsItem=this.cartList.find(item=>item.goods_id=cartItem.goods_id)
            if(!goodsItem){
                this.cartList.push(cartItem)
            } else{
                goodsItem.num+=1
            }
        },
        DEL_CART_ITEM(value){
            if(typeof value=='number'){
                this.cartList.splice(value,1)
            } else{
                value.num-=1
            }
        },
        ALL_CHECK(value){
            this.cartList.forEach(item=>item.check=value)
        }
    },
    getters:{
        allCount(){
            return this.cartList.reduce((aa,bb)=>{
                if(bb.check){
                    return aa+bb.num
                } else{
                    return aa
                }
            },0)
        },
        allPrice(){
            return this.cartList.reduce((aa,bb)=>{
                if(bb.check){
                    return aa+bb.num*bb.goods_price*100
                } else{
                    return aa
                }
            },0)
        },
        orderList(){
            this.cartList.filter(item=>item.check)
        }
    }
})
